package com.ygy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ygy.entity.Users;
import com.ygy.service.IUsersService;
import com.ygy.utils.JwtUtil;
import com.ygy.utils.Md5Util;
import com.ygy.utils.Result;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Ye
 * @since 2024-03-14
 */

@RestController
@Validated
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUsersService usersService;


    //注册用户
    @PostMapping("/register")
    public Result register(@RequestBody Users users) {
        System.out.println(users+"user");
        //重复性判断
        String username = users.getUsername();
        QueryWrapper wrapper = new QueryWrapper<Users>()
                .eq("username", username);
        // 查询操作
        if (usersService.getOne(wrapper) != null) {
            //用户名已经存在
            return Result.error(users.getUsername()+"用户名存在");
        }
        //默认头像
        users.setAvatar("http://localhost:8081/views?fileName=aa4ca4bb-19f2-4161-b841-0fb28034f413.jpg");
        //加密
        users.setPassword(Md5Util.getMD5String(users.getPassword()));
        boolean save = usersService.save(users);

        //  判断
        if (save) {
            return Result.success(users,users.getUsername()+"注册成功");
        } else {
            return Result.error(users.getUsername()+"注册失败");
        }
    }

    //删除用户
    @DeleteMapping("/delete")
    public Result delete(Long userId) throws IOException {
        System.out.println();
        //  通过调用业务层根据主键来进行删除
        boolean delete = usersService.removeById(userId);
        if (delete) {
            // 操作成功，则跳转查询新的数据
            return Result.success();
        }
        return Result.error("删除失败");
    }


    //批量删除
    @PostMapping("/delete")
    public Result delete(@RequestBody List<Long> userId) throws IOException {
        for (Long userIds : userId) {
            boolean delete = usersService.removeById(userIds);
            if (!delete) {
                return Result.error("删除失败");
            }
        }
        return Result.success();
    }

    //修改个人基本资料
    @PostMapping("/update")
    public Result update(@RequestBody Users users, HttpServletRequest reques) {
        Integer userId = users.getUserId();
            System.out.println("修改接口打印"+users);

        boolean update = usersService.saveOrUpdate(users);
        //  判断
        if (update) {
            return Result.success(users,users.getUsername()+"用户信息更新成功");
        } else {
            return Result.error("失败");
        }
    }

    //修改密码基本资料
    @PostMapping("/updatePwd")
    public Result updatePwd(@RequestBody Users users) {
        Integer userId = users.getUserId();
        System.out.println("修改接口打印"+users);

        //  通过调用业务层来实现修改的业务功能【根据主键来进行修改】
        users.setPassword(Md5Util.getMD5String(users.getPassword()));
        boolean update = usersService.saveOrUpdate(users);
        //  判断
        if (update) {
            return Result.success(users,users.getUsername()+"用户修改密码成功");
        } else {
            return Result.error("失败");
        }
    }

    //查询用户
    @GetMapping("/list")
    public List<Users> list(HttpServletRequest request) {
        // 如何查询user的数据？
        List<Users> userList = usersService.list();
        return userList;
    }

    //查询单个用户
    @Transactional
    @GetMapping("/userId")
    public Result<Users>  getUser(@RequestParam Integer userId){
        System.out.println("========进来查询"+userId);
         Users users = usersService.getById(userId);
        // 检查用户是否存在
        if (users == null) {
            return Result.error("信息有误");
        }
        System.out.println(users+"=======");
        // 如果用户存在，返回用户信息
        return Result.success(users);

    }

    //登录
    @PostMapping("/loginUser")
    public Result loginUser(@RequestBody Users users) {
        System.out.println(users); // Debug: 输出接收到的用户信息

        String password = users.getPassword();
        String username = users.getUsername();

        //  输出原始密码
        System.out.println("Original password: " + password);

        // 加密
        password = Md5Util.getMD5String(password);

        //  输出加密后的密码
        System.out.println("Encrypted password: " + password);

        QueryWrapper<Users> wrapper = new QueryWrapper<Users>().eq("username", username);

        // 登录查询操作
        Users user = usersService.getOne(wrapper);

        if (user == null) {
            return Result.error("账号不存在");
        }

        // Debug: 输出数据库中的密码与输入密码
        System.out.println("DB password: " + user.getPassword() + ", Input password: " + password);

        // 判断密码是否正确
        if (password.equals(user.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getUserId());
            claims.put("username", user.getUsername());
            String token = JwtUtil.genTonken(claims);

            Map<String, Object> res = new HashMap<>();
            res.put("user", user);
            res.put("token", token);

            return Result.success(res, "登录成功");
        }
        return Result.error("密码错误");
    }



    //分页查询
    @GetMapping("/page")
    public IPage<Users> findPage(@RequestParam Integer pageNum,
                                 @RequestParam Integer pageSize,
                                 @RequestParam(defaultValue = "") String username) {
        IPage<Users> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username", username);
        return usersService.page(page, queryWrapper);
    }



    //单个用户信息查询
        @GetMapping("/{id}")
        public Result<Users> getUserById(@PathVariable Integer id) {
            Users user = usersService.getById(id);
            return  Result.success(user);
    }

}
